package com.lantosec.hmrp.modules.category.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.kit.PageVO;
import com.lantosec.hmrp.core.util.DateUtils;
import com.lantosec.hmrp.modules.category.entity.*;
import com.lantosec.hmrp.modules.category.mapper.AssetsCheckNoteMapper;
import com.lantosec.hmrp.modules.category.service.IAssetsCheckNoteService;
import com.lantosec.hmrp.modules.category.service.IAssetsInfoService;
import com.lantosec.hmrp.modules.system.service.ISysAreaService;
import com.lantosec.hmrp.modules.system.service.ISysDeptService;
import com.lantosec.hmrp.modules.uploads.service.ISysUploadsService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 盘点记录 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-04-02
 */
@Service
@Primary
@Log4j2
@SuppressWarnings("all")
public class AssetsCheckNoteServiceImpl extends ServiceImpl<AssetsCheckNoteMapper, AssetsCheckNote> implements IAssetsCheckNoteService {

    @Autowired
    private IAssetsInfoService assetsInfoService;

    @Autowired
    private ISysUploadsService uploadsService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysAreaService areaService;



    @Override
    public Page<AssetsCheckNote> normalUnaudited(PageVO<AssetsCheckNote> page, AuditInfo info) {
        PageVO<AssetsCheckNote> param  = baseMapper.normalUnaudited(page,info);
         param.getRecords().forEach(it->{
             it.setAssetsName(assetsInfoService.getById(it.getAssetsId()).getAssetsName());
             it.setAssetsState(assetsInfoService.getById(it.getAssetsId()).getAssetsState());
             if(StringUtils.isNotEmpty(it.getDeptId())){
                 it.setDeptName(deptService.getById(it.getDeptId()).getDeptName());
             }else{
                 it.setAreaName(areaService.getById(it.getAreaId()).getAreaName());
             }
         });
        return page.setRecords(param.getRecords());
    }

    @Override
    public Page<AssetsCheckNote> changeUnaudited(PageVO<AssetsCheckNote> page, AuditInfo info) {
        PageVO<AssetsCheckNote> param  = baseMapper.changeUnaudited(page,info);
        param.getRecords().forEach(it->{
            it.setAssetsName(assetsInfoService.getById(it.getAssetsId()).getAssetsName());
            it.setAssetsState(assetsInfoService.getById(it.getAssetsId()).getAssetsState());
            if(StringUtils.isNotEmpty(it.getDeptId())){
                it.setDeptName(deptService.getById(it.getDeptId()).getDeptName());
            }else{
                it.setAreaName(areaService.getById(it.getAreaId()).getAreaName());
            }
        });
        return page.setRecords(param.getRecords());
    }

    @Override
    public Page<AssetsCheckNote> audited(PageVO<AssetsCheckNote> page, AuditInfo info) {
        List list = new ArrayList();
        PageVO<AssetsCheckNote> param = baseMapper.selectPage(page, new QueryWrapper<AssetsCheckNote>()
                .eq("plan_id", info.getPlanId())
                .eq(StringUtils.isNotEmpty(info.getDeptId()), "dept_id", info.getDeptId())
                .eq(StringUtils.isNotEmpty(info.getAreaId()), "area_id", info.getAreaId())
                .eq(StringUtils.isNotEmpty(info.getCheckType()), "check_type", info.getCheckType())
                .eq(StringUtils.isNotEmpty(info.getCategoryId()), "category_id", info.getCategoryId())
                .in("review_state", 1,2));
        param.getRecords().forEach(it -> {
            String assetsId = it.getAssetsId();
            //资产状态
            String assetsState = assetsInfoService.getById(assetsId).getAssetsState();
            it.setAssetsState(assetsState);
            //盘点资产状态
            it.setCheckState(it.getCheckState());
            //固定资产名称
            String assetsName = assetsInfoService.getById(it.getAssetsId()).getAssetsName();
            it.setAssetsName(assetsName);
            //区域或部门名称
            if(StringUtils.isNotEmpty(it.getDeptId())){
                it.setDeptName(deptService.getById(it.getDeptId()).getDeptName());
            }else{
                it.setAreaName(areaService.getById(it.getAreaId()).getAreaName());
            }
        });
        return page.setRecords(param.getRecords());
    }

    @Override
    public void check(Map<String, Object> param) {
        String planId = (String)param.get("planId");
        List assetsIds  = (List) param.get("assetsIds");
        String checkFlag = (String) param.get("checkFlag");
        //更新盘点记录表审核状态
        assetsIds.forEach(it->{
            AssetsCheckNote note = new AssetsCheckNote();
            if("0".equals(checkFlag)){
                note.setReviewState(1);
            }else{
                note.setReviewState(2);
            }
            note.setCheckTime(DateUtils.format(new Date()));
            note.setCheckUser("管理员");
            note.setCheckUserId("superuser");
            baseMapper.update(note,new QueryWrapper<AssetsCheckNote>()
            .eq("assets_id",it));
            //更新资产信息表物资信息
            AssetsCheckNote info = baseMapper.selectOne(new QueryWrapper<AssetsCheckNote>()
                    .eq(String.valueOf(AssetsCheckNote.ColName.plan_id), planId)
                    .eq(String.valueOf(AssetsCheckNote.ColName.assets_id), it));
            info.setSummaryNumber(null == info.getSummaryNumber()?1:info.getSummaryNumber());
            baseMapper.updateInfo(info.getCheckState(),info.getSummaryNumber(),info.getAssetsId());
        });


    }

    @Override
    public Page<AssetsCheckNote> queryAssetsCheckNoteList(
            PageVO<AssetsCheckNote> page, String areaId, String deptId,
            String checkUserName, String planId, String checkType) {
        List urlList = new ArrayList();
        PageVO<AssetsCheckNote> param = baseMapper.selectPage(page, new QueryWrapper<AssetsCheckNote>()
                .eq(String.valueOf(AssetsCheckNote.ColName.plan_id), planId)
                .eq(StringUtils.isNotEmpty(areaId), String.valueOf(AssetsCheckNote.ColName.area_id), areaId)
                .eq(StringUtils.isNotEmpty(deptId), String.valueOf(AssetsCheckNote.ColName.dept_id), deptId)
                .like(StringUtils.isNotEmpty(checkUserName), String.valueOf(AssetsCheckNote.ColName.check_user), checkUserName)
                .eq(StringUtils.isNotEmpty(checkType), String.valueOf(AssetsCheckNote.ColName.check_type), checkType));

        for (AssetsCheckNote it : param.getRecords()) {
            String photoList = it.getPhotoList();
            urlList = uploadsService.pictureUrl(photoList);
            //盘点图片
            it.setPictureUrl(urlList);
            //查询物资名称及部门或区域名称
            String assetsName = assetsInfoService.getById(it.getAssetsId()).getAssetsName();
            it.setAssetsName(assetsName);
            if(StringUtils.isNotEmpty(it.getDeptId())){
                String deptName = deptService.getById(it.getDeptId()).getDeptName();
                it.setDeptName(deptName);
            }else{
                String areaName = areaService.getById(it.getAreaId()).getAreaName();
                it.setAreaName(areaName);
            }
        }
        return page.setRecords(param.getRecords());
    }

    @Override
    public List<AssetsCheckNote> querySingleCheckList(String assetsId) {
        List<AssetsCheckNote> param = baseMapper.selectList(new QueryWrapper<AssetsCheckNote>()
                .eq(String.valueOf(AssetsCheckNote.ColName.assets_id), assetsId));
        param.forEach(it->{
            String photoList = it.getPhotoList();
            if(StringUtils.isNotEmpty(photoList)){
                List list = uploadsService.pictureUrl(photoList);
                it.setCheckPictureUrl(list);
            }
        });
        return param;
    }

    @Override
    public List<AssetsImage> queryHistoryPic(String assetsId) {
        String param = baseMapper.queryHistoryPic(assetsId);
        if(StringUtils.isNotEmpty(param)){
            return uploadsService.assetsPictureUrl(assetsId);
        }else{
            return null;
        }
    }

    @Override
    public Map summarize(String planId, String deptId,String areaId) {
        Map result = new HashMap();
        Map rfidMap = new HashMap();
        Map noLabel = new HashMap();
        Integer checkSummaryNumber = 0;
        List<AssetsCheckNote> list = null;
        String categoryList = baseMapper.categoryList(planId);
        AssetsCount countForLableType = assetsInfoService.getCountForLableType(deptId, areaId,categoryList);
        AssetsCount checkCount = assetsInfoService.getCheckCount(planId,deptId, areaId,categoryList);
        //资产汇总数
         Integer summaryNumber = baseMapper.deptSummaryNumber(deptId,areaId,categoryList);
        //已完成盘点的资产汇总数
        list = baseMapper.getTotalNum(planId,deptId,areaId);
        for (AssetsCheckNote note : list) {
            String assetsId = note.getAssetsId();
            checkSummaryNumber += baseMapper.checkSummaryNumber(assetsId);
        }
        rfidMap.put("rfidCount",countForLableType.getRfidCount());
        rfidMap.put("rfidCheckCount",checkCount.getRfidCheckCount());
        rfidMap.put("metalCount",countForLableType.getMetalCount());
        rfidMap.put("metalCheckCount",checkCount.getMetalCheckCount());
        result.put("RFID",rfidMap);

        noLabel.put("summaryNumber",summaryNumber== null?0:summaryNumber );
        noLabel.put("checkSummaryNumber",checkSummaryNumber );
        noLabel.put("labelCount",countForLableType.getLabelCount());
        noLabel.put("labelCheckCount",checkCount.getLabelCheckCount());
        result.put("other",noLabel);

        return result;
    }

    @Override
    public Map complete(String planId,String deptId,String areaId) {
        List<AssetsInfo> infos = new ArrayList<>();
        List<AssetsInfo> diffInfo = new ArrayList<>();
        List<AssetsInfo> sameInfo = new ArrayList<>();
        Map map = new HashMap();
        Map result = new HashMap();
        List<AssetsInfo> unfinished = null;
        List<AssetsCheckNote> param = null;
        String categoryList = baseMapper.categoryList(planId);
        //该条盘点计划已完成盘点的固定资产
        param = baseMapper.getFinishList(planId,areaId,deptId,categoryList);
        param.forEach(it->{
            String assetsId = it.getAssetsId();
            AssetsInfo info = assetsInfoService.getById(assetsId);
            info.setCheckState(it.getCheckState());
            info.setCheckUser(it.getCheckUser());
            info.setCheckTime(it.getCheckTime());
            String photoList = info.getPhotoList();
            if(StringUtils.isNotEmpty(photoList)){
                info.setPictureUrl(uploadsService.pictureUrl(photoList));
            }
            infos.add(info);
        });
        //部门未完成
        if(StringUtils.isNotEmpty(deptId)){
            unfinished = baseMapper.queryDeptUnfinished(planId,deptId,categoryList);
        }else{
            unfinished = baseMapper.queryAreaUnfinished(planId,areaId,categoryList);
        }
        unfinished.forEach(it->{
            String photoList = it.getPhotoList();
            if(StringUtils.isNotEmpty(photoList)){
                it.setPictureUrl(uploadsService.pictureUrl(photoList));
            }
        });
        //比较两个list的差异
        for (AssetsInfo info : infos) {
            map.put(info.getAssetsId(),1);
        }
        for (AssetsInfo info : unfinished) {
            if(map.get(info.getAssetsId()) == null){
                //未完成
                diffInfo.add(info);
            }else{
                //已完成
                sameInfo.add(info);
            }
        }
        result.put("finished",infos);
        result.put("unfinished",diffInfo);
        return result;
    }

    @Override
    public AssetsCheckNote getInfo(String assetsId,String planId) {
        AssetsCheckNote note = baseMapper.selectOne(new QueryWrapper<AssetsCheckNote>()
                .eq(String.valueOf(AssetsCheckNote.ColName.plan_id), planId)
                .eq(String.valueOf(AssetsCheckNote.ColName.assets_id), assetsId));
        //获取盘点记录表盘点图片
        if(StringUtils.isNotEmpty(note.getPhotoList())){
            List list = uploadsService.pictureUrl(note.getPhotoList());
            note.setCheckPictureUrl(list);
        }
        return note;
    }

    @Override
    public void bulkInventory(Map<String, Object> map) {
        String param = (String) map.get("param");
        List<AssetsCheckNote> infos = JSON.parseArray(param, AssetsCheckNote.class);
        infos.forEach(it->{
            String planId = it.getPlanId();
            String assetsId = it.getAssetsId();
            Integer count = baseMapper.selectCount(new QueryWrapper<AssetsCheckNote>()
            .eq(String.valueOf(AssetsCheckNote.ColName.plan_id),it.getPlanId())
            .eq(String.valueOf(AssetsCheckNote.ColName.assets_id),it.getAssetsId()));
            if(count != 0){
                return;
            }else{
                //todo
                it.setCheckTime(DateUtils.format(new Date()));
                it.setCheckUserId("superuser");
                it.setCheckUser("管理员");
                it.setReviewState(0);
                it.setCategoryId(assetsInfoService.getById(assetsId).getCategoryId());
                if(null == it.getSummaryNumber()){
                    it.setSummaryNumber(1);
                }
                baseMapper.insert(it);
            }
        });
    }

    @Override
    public Map completeByLableType(String planId, String deptId, String areaId, String lableType) {
        List<AssetsInfo> infos = new ArrayList<>();
        List<AssetsInfo> diffInfo = new ArrayList<>();
        List<AssetsInfo> sameInfo = new ArrayList<>();
        Map map = new HashMap();
        Map result = new HashMap();
        List<AssetsInfo> list = null;
        List<AssetsCheckNote> param = null;
        String categoryList = baseMapper.categoryList(planId);
        //该条盘点计划已完成盘点的固定资产
        param = baseMapper.getFinishList(planId,areaId,deptId,categoryList);
        param.forEach(it->{
            String assetsId = it.getAssetsId();
            AssetsInfo info = assetsInfoService.getById(assetsId);
            info.setCheckState(it.getCheckState());
            info.setCheckUser(it.getCheckUser());
            info.setCheckTime(it.getCheckTime());
            String photoList = info.getPhotoList();
            if(StringUtils.isNotEmpty(photoList)){
                info.setPictureUrl(uploadsService.pictureUrl(photoList));
            }
            infos.add(info);

        });

        //无标签
        if("0".equals(lableType)){
            list = assetsInfoService.getAssetsLableList(deptId,areaId,categoryList);
            list.forEach(it->{
                if(StringUtils.isNotEmpty(it.getPhotoList())){
                    it.setPictureUrl(uploadsService.pictureUrl(it.getPhotoList()));
                }
            });
        }else{  //RFID标签
            list = assetsInfoService.getCountByRfid(deptId,areaId,categoryList);
            list.forEach(it->{
                if(StringUtils.isNotEmpty(it.getPhotoList())){
                    it.setPictureUrl(uploadsService.pictureUrl(it.getPhotoList()));
                }
            });
        }
        //比较两个list的差异
        for (AssetsInfo info : infos) {
            map.put(info.getAssetsId(),1);
        }
        for (AssetsInfo info : list) {
            if(map.get(info.getAssetsId()) == null){
                //未完成
                diffInfo.add(info);
            }else{
                //已完成
                sameInfo.add(info);
            }
        }
        result.put("finished",infos);
        result.put("unfinished",diffInfo);
        return result;
    }
}
